package me.panpf.sketch.sample.vt.adapter;

import me.panpf.sketch.Sketch;
import me.panpf.sketch.SketchImageView;
import me.panpf.sketch.display.TransitionImageDisplayer;
import me.panpf.sketch.sample.vt.ResourceTable;
import me.panpf.sketch.sample.vt.ui.listcontainer.RefreshListContainer;
import me.panpf.sketch.sample.vt.utils.FileUtil;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.media.image.PixelMap;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * description :
 *
 * @since : 2021/6/3
 */
public class VideoListAdapter extends RefreshListContainer.RecyclerAdapter<me.panpf.sketch.sample.vt.bean.VideoInfo> {
    private Context mContext;
    private List<me.panpf.sketch.sample.vt.bean.VideoInfo> dataList;
    private EventRunner eventRunner = EventRunner.getMainEventRunner();
    private MyHandler mHandler = new MyHandler(eventRunner);
    private final static String DISPATCHERNAME = "parallelTaskDispatcher";

    /**
     * 根据context 和 dataList 创建 VideoListAdapter对象
     *
     * @param context   context
     * @param dataList  视频数据集合
     * @param mLayoutId mLayoutId
     */
    public VideoListAdapter(Context context, List<me.panpf.sketch.sample.vt.bean.VideoInfo> dataList, int mLayoutId) {
        super(context, dataList, mLayoutId);
        mContext = context;
        this.dataList = dataList;
    }

    @Override
    public List<me.panpf.sketch.sample.vt.bean.VideoInfo> getData() {
        return super.getData();
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public me.panpf.sketch.sample.vt.bean.VideoInfo getItem(int position) {
        return super.getItem(position);
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer parent) {
        return super.getComponent(position, convertComponent, parent);
    }

    @Override
    public void setNumColumns(int numColumns) {
        super.setNumColumns(numColumns);
    }

    @Override
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        super.setOnItemClickListener(onItemClickListener);
    }

    @Override
    public void bind(ViewHolder holder, me.panpf.sketch.sample.vt.bean.VideoInfo videoInfo, int position) {
        holder.<SketchImageView>getView(ResourceTable.Id_image_myVideoItem_icon).getOptions()
                .setLoadingImage(ResourceTable.Media_image_loading).setDisplayer(new TransitionImageDisplayer());
        // 填充数据
        PixelMap firstPixelMap = videoInfo.getPixelMap();
        if (videoInfo.getPixelMap() == null) {
            // 异步加载缩略图，防止卡顿
            TaskDispatcher dispatcher = mContext.createParallelTaskDispatcher(DISPATCHERNAME, TaskPriority.DEFAULT);
            dispatcher.asyncDispatch(() -> getFirstPixelMap(videoInfo.getId() + "", position));
            Sketch.with(mContext).displayFromResource(ResourceTable.Media_ic_launcher,
                    holder.<SketchImageView>getView(ResourceTable.Id_image_myVideoItem_icon));
        } else {
            holder.<SketchImageView>getView(ResourceTable.Id_image_myVideoItem_icon).setPixelMap(firstPixelMap);
        }
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        SimpleDateFormat sdfDuration = new SimpleDateFormat("mm:ss");
        String date = sdfDate.format(new Date(videoInfo.getDate() * 1000));
        String duration = sdfDuration.format(new Date(videoInfo.getDuration()));

        holder.<Text>getView(ResourceTable.Id_text_myVideoItem_duration).setText(duration);

        holder.<Text>getView(ResourceTable.Id_text_myVideoItem_no).setText(String.valueOf(position + 1));

        holder.<Text>getView(ResourceTable.Id_text_myVideoItem_name)
                .setText(videoInfo.getTitle());

        holder.<Text>getView(ResourceTable.Id_text_myVideoItem_size)
                .setText(FileUtil.formatFileSize(videoInfo.getSize()));

        holder.<Text>getView(ResourceTable.Id_text_myVideoItem_date)
                .setText(date);
    }

    /**
     * 设置新的数据
     *
     * @param list 新的数据
     */
    public void setNewData(List<me.panpf.sketch.sample.vt.bean.VideoInfo> list) {
        dataList.clear();
        addData(list);
    }

    /**
     * 添加数据
     *
     * @param list 要添加的数据
     */
    public void addData(List<me.panpf.sketch.sample.vt.bean.VideoInfo> list) {
        dataList.addAll(list);
    }

    /**
     * 视频文件获取第一帧PixMap
     *
     * @param fileId   视频文件ID
     * @param position item position
     */
    private void getFirstPixelMap(String fileId, int position) {
        PixelMap resultPixelMap = FileUtil.getFirstPixelMap(mContext, fileId);
        if (position < dataList.size()) {
            dataList.get(position).setPixelMap(resultPixelMap);
            InnerEvent innerEvent = InnerEvent.get();
            innerEvent.eventId = 100;
            innerEvent.object = position + 1; // 由于refreshView会占第0行，所以刷新的时候需要+1
            mHandler.sendEvent(innerEvent);
        }
    }

    private class MyHandler extends EventHandler {
        private MyHandler(EventRunner runner) {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event.eventId == 100) {
                notifyDataSetItemChanged((Integer) event.object);
            }
        }
    }
}